package com.xyd.wechat.service.impl;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.xyd.wechat.common.MsgTypeEnum;
import com.xyd.wechat.service.CustomerService;
import com.xyd.wechat.service.MaterialService;
import com.xyd.wechat.service.SubscribeService;
import com.xyd.wechat.vo.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SubscribeServiceImpl implements SubscribeService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MaterialService materialService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private XmlMapper xmlMapper;

    private final String imageName = "关注后回复.png";

    @Override
    public String welcome(Message message) {
        String mediaId = materialService.getMediaId(MsgTypeEnum.IMAGE.getType(), imageName);
        Message responseMsg = new Message();
        responseMsg.setToUserName(message.getToUserName());
        responseMsg.setFromUserName(message.getFromUserName());
        responseMsg.setCreateTime(message.getCreateTime());
        responseMsg.setMsgType(MsgTypeEnum.IMAGE.getType());
        responseMsg.setMediaId(mediaId);
        // 响应 返回
        try {
            String rStr = xmlMapper.writeValueAsString(responseMsg);
            logger.info("关注事件 -- 自动回复响应内容：{}", rStr);
            return rStr;
        } catch (Exception e) {
            logger.error("关注事件 -- 自动回复（返回结果时）发生异常。", e);
            return null;
        } finally {
            customerService.sendToUser(responseMsg);
        }
    }
}
